package com.obst.tracenote.listcontroller;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import com.obst.tracenote.adapter.CommonAdapter;
import com.obst.tracenote.data.ListData;
import com.obst.tracenote.util.MyServer;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ListView;

public class ListController {

	private MyServer mServer;
	private Activity mActivity;
	private ProgressDialog mLoader; // Loading Dialog
	private ArrayList<ListData> mDataList = null;
	private ListView mView;
	private static int mServerMethod;

	private CommonAdapter mAdapter;

	public ListController(Activity activity, ListView v, CommonAdapter adapter) {
		mView		= v;
		mActivity	= activity;
		mDataList	= new ArrayList<ListData>();
		
		mAdapter	= adapter;
	}

	public void setMethod(int method) {
		ListController.mServerMethod = method;
	}
	public void setListData(ArrayList<ListData> list) {
		mDataList = list;
	}
	public void loadDataFromJson() {
		viewProgress();
		Thread thread = new Thread(new Runnable() {
			public void run() {
				if (mDataList.size() == 0) {
					mServer = new MyServer(mActivity,
							ListController.mServerMethod);
					JSONObject tList = mServer.getJSON();
					try {
						ListData tmpMyList;
						JSONArray rtnArray = tList.getJSONArray("data");
						int tmpLen = rtnArray.length();
						JSONObject jo = new JSONObject();
						for (int i = 0; i < tmpLen; i++) {
							jo = rtnArray.getJSONObject(i);
							tmpMyList = new ListData(jo);
							mDataList.add(tmpMyList);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				handler.sendEmptyMessage(0);
			}
		});
		thread.start();
	}

	private void viewProgress() {
		mLoader = ProgressDialog.show(mActivity, "", "loading...", true, false);
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (mLoader.isShowing()) {
				mLoader.dismiss();
			}
			ListController.this.addView();
		}
	};

	public void addView() {
		try {
			mView.setAdapter(mAdapter);
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}

	public void showView() {
		mView.setVisibility(View.VISIBLE);
	}

	public void hideView() {
		mView.setVisibility(View.INVISIBLE);
	}
}
